using Microsoft.Extensions.Logging;
using SmartMedicalRAG.Core.Models;

namespace SmartMedicalRAG.Core.Services;

/// <summary>
/// RAG生成服务实现
/// </summary>
public class RAGGenerationService : IRAGGenerationService
{
    private readonly ILogger<RAGGenerationService> _logger;
    private readonly IKnowledgeRetrievalService _retrievalService;
    private readonly ILLMService _llmService;
    private readonly IPromptEngineer _promptEngineer;
    private readonly IFactChecker _factChecker;

    public RAGGenerationService(
        ILogger<RAGGenerationService> logger,
        IKnowledgeRetrievalService retrievalService,
        ILLMService llmService,
        IPromptEngineer promptEngineer,
        IFactChecker factChecker)
    {
        _logger = logger;
        _retrievalService = retrievalService;
        _llmService = llmService;
        _promptEngineer = promptEngineer;
        _factChecker = factChecker;
    }

    public async Task<TriageRecommendation> GenerateTriageRecommendationAsync(PatientData patientData)
    {
        try
        {
            _logger.LogInformation("开始生成分诊建议，患者ID: {PatientId}", patientData.Id);
            
            // 1. 构建查询
            var query = await BuildQueryAsync(patientData);
            
            // 2. 知识检索
            var retrievalResult = await _retrievalService.HybridSearchAsync(query);
            
            // 3. 动态提示工程
            var prompt = await _promptEngineer.BuildPromptAsync(patientData, retrievalResult);
            
            // 4. LLM生成
            var llmResponse = await _llmService.GenerateAsync(prompt);
            
            // 5. 事实验证
            var isValid = await _factChecker.ValidateAsync(llmResponse, retrievalResult);
            
            if (!isValid)
            {
                _logger.LogWarning("LLM生成结果验证失败，重新生成");
                return await HandleInvalidResponseAsync(patientData, retrievalResult);
            }
            
            // 6. 构建分诊建议
            var recommendation = await BuildRecommendationAsync(llmResponse, retrievalResult);
            
            _logger.LogInformation("分诊建议生成完成，推荐科室: {Department}, 优先级: {Priority}", 
                recommendation.RecommendedDepartment, recommendation.Priority);
            
            return recommendation;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成分诊建议失败");
            throw;
        }
    }

    public async Task<bool> ValidateRecommendationAsync(TriageRecommendation recommendation)
    {
        try
        {
            // 检查建议的合理性
            var logicalCheck = await CheckLogicalConsistencyAsync(recommendation);
            
            // 检查与检索结果的一致性
            var consistencyCheck = await CheckConsistencyWithRetrievalAsync(recommendation);
            
            // 检查伦理合规性
            var ethicalCheck = await CheckEthicalComplianceAsync(recommendation);
            
            var isValid = logicalCheck && consistencyCheck && ethicalCheck;
            
            _logger.LogInformation("分诊建议验证结果: 逻辑性={Logical}, 一致性={Consistency}, 合规性={Ethical}, 总体={IsValid}",
                logicalCheck, consistencyCheck, ethicalCheck, isValid);
            
            return isValid;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证分诊建议失败");
            return false;
        }
    }

    public async Task<List<string>> GetTraceabilitySourcesAsync(TriageRecommendation recommendation)
    {
        var sources = new List<string>();
        
        // 添加指南章节引用
        if (recommendation.GuidelineReferences != null)
        {
            sources.AddRange(recommendation.GuidelineReferences);
        }
        
        // 添加相似病例ID
        if (recommendation.SimilarCaseIds != null)
        {
            sources.AddRange(recommendation.SimilarCaseIds.Select(id => $"Case_{id}"));
        }
        
        // 添加实时数据来源
        if (recommendation.RealTimeDataSources != null)
        {
            sources.AddRange(recommendation.RealTimeDataSources);
        }
        
        _logger.LogInformation("获取追溯来源完成，共 {SourceCount} 个来源", sources.Count);
        return sources;
    }

    private async Task<string> BuildQueryAsync(PatientData patientData)
    {
        var queryBuilder = new System.Text.StringBuilder();
        
        // 添加患者主诉
        if (!string.IsNullOrEmpty(patientData.ChiefComplaint))
        {
            queryBuilder.AppendLine($"主诉: {patientData.ChiefComplaint}");
        }
        
        // 添加症状描述
        if (patientData.Symptoms != null && patientData.Symptoms.Any())
        {
            queryBuilder.AppendLine($"症状: {string.Join(", ", patientData.Symptoms)}");
        }
        
        // 添加生理指标
        if (patientData.VitalSigns != null)
        {
            queryBuilder.AppendLine($"血压: {patientData.VitalSigns.BloodPressure}");
            queryBuilder.AppendLine($"心率: {patientData.VitalSigns.HeartRate}");
            queryBuilder.AppendLine($"体温: {patientData.VitalSigns.Temperature}");
        }
        
        // 添加病史
        if (!string.IsNullOrEmpty(patientData.MedicalHistory))
        {
            queryBuilder.AppendLine($"病史: {patientData.MedicalHistory}");
        }
        
        return queryBuilder.ToString();
    }

    private async Task<TriageRecommendation> HandleInvalidResponseAsync(PatientData patientData, RetrievalResult retrievalResult)
    {
        // 重新生成或标记为需要人工审核
        _logger.LogWarning("LLM生成结果无效，标记为需要人工审核");
        
        return new TriageRecommendation
        {
            RecommendedDepartment = "待人工审核",
            Priority = TriagePriority.Urgent,
            Reasoning = "系统生成结果需要人工审核",
            Confidence = 0.0f
        };
    }

    private async Task<TriageRecommendation> BuildRecommendationAsync(object llmResponse, RetrievalResult retrievalResult)
    {
        // 这里应该解析LLM响应并构建分诊建议
        // 简化实现
        return new TriageRecommendation
        {
            RecommendedDepartment = "心血管内科",
            Priority = TriagePriority.Emergency,
            Reasoning = "基于检索到的医学知识分析",
            Confidence = 0.95f
        };
    }

    private async Task<bool> CheckLogicalConsistencyAsync(TriageRecommendation recommendation)
    {
        // 检查建议的合理性
        return true;
    }

    private async Task<bool> CheckConsistencyWithRetrievalAsync(TriageRecommendation recommendation)
    {
        // 检查与检索结果的一致性
        return true;
    }

    private async Task<bool> CheckEthicalComplianceAsync(TriageRecommendation recommendation)
    {
        // 检查伦理合规性
        return true;
    }
}

/// <summary>
/// 知识检索服务接口
/// </summary>
public interface IKnowledgeRetrievalService
{
    Task<RetrievalResult> SemanticSearchAsync(string query, int topK = 5);
    Task<RetrievalResult> HybridSearchAsync(string query, int topK = 5);
    Task<RetrievalResult> MultiHopReasoningAsync(string query, int maxHops = 3);
    Task UpdateKnowledgeBaseAsync(KnowledgeUpdate update);
}

/// <summary>
/// LLM服务接口
/// </summary>
public interface ILLMService
{
    Task<object> GenerateAsync(string prompt);
}

/// <summary>
/// 提示工程师接口
/// </summary>
public interface IPromptEngineer
{
    Task<string> BuildPromptAsync(PatientData patientData, RetrievalResult retrievalResult);
}

/// <summary>
/// 事实验证器接口
/// </summary>
public interface IFactChecker
{
    Task<bool> ValidateAsync(object llmResponse, RetrievalResult retrievalResult);
} 